﻿#建议保存编码为：bom头 + utf8
#

param
(
	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[ValidateScript({
			if ($_[0] -eq '/')
			{
				return $true
			}
			else
			{
				Write-Error '错误：必须以“/”开头'
			}
		})]
	[string]$路由路径, # '/abc'  '/abc/*'   '/index.html'

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[string]$上游id, # '192.168.1.2:333' 这里应该为string

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[string]$路由名字,

	[string]$endpoints #后面不要有/
	
	[string]$username = '',

	[string]$password = '',

	[string]$pfx
)

if ( ($null -eq $endpoints) -or ($endpoints -eq '') )
{
	if ( ($null -eq $global:endpoints) -or ($global:endpoints -eq '') )
	{
		Write-Error '错误：endpoints值错误。返回码 21'
		exit 21
	}
	else
	{
		$endpoints = $global:endpoints
	}
}

$body = @{
	id          = $id = "{0}" -f $(& "${PSScriptRoot}/uint64随机数.ps1")
	name        = "$路由名字"
	uri         = "$路由路径"
	upstream_id = "$上游id"
	methods     = "GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE","PURGE"
	timeout     = @{"connect" = 9; "send" = 9; "read" = 9 }
	status      = 1
} | ConvertTo-Json -Depth 5
Write-Verbose $body

#问：这个脚本谁写的？有问题找谁技术支持��
#答：QQ群号=722528388
#名称=k4t国产k8s群1
#华之夏，脚之巅，有我ps1片天！
#专门教学win，linux通用的ps1脚本。不想学也可以，入群用红包求写脚本。
$k = "/apisix/routes/{0}" -f $id

if ($pfx)
{
	if ($PSVersionTable.psversion.major -lt 7)
	{
		Write-Error '错误：win7需要powershell v7.2.x。win10及以上需要powershell v7.4.x。返回码993'
		exit 993
	}

	try
	{
		$null = & "${PSScriptRoot}/put-k8sKey.ps1" -endpoints $endpoints -pfx $pfx -k $k -v $body
		Write-Host "信息：添加路由成功，路由id：" -ForegroundColor Green
		return $id
	}
	catch
	{
		Write-Error '错误：添加路由失败，返回码1'
		exit 1
	}
}
else
{
	try
	{
		$null = & "${PSScriptRoot}/put-etcdKey.ps1" -endpoints $endpoints -username $username -password $password -k $k -v $body
		Write-Host "信息：添加路由成功，路由id：" -ForegroundColor Green
		return $id
	}
	catch
	{
		Write-Error '错误：添加路由失败，返回码1'
		exit 1
	}
}


<#
{
  "uri": "/test1",
  "name": "测试路由",
  "methods": [
    "GET",
    "POST",
    "PUT",
    "DELETE",
    "PATCH",
    "HEAD",
    "OPTIONS",
    "CONNECT",
    "TRACE",
    "PURGE"
  ],
  "upstream_id": "5558162174925864153",
  "status": 1
}

#>
